﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using BLL;

namespace DAL.Managers
{
    /// <summary>
    /// The manager for the object Tag
    /// </summary>
    public class TagManager
    {
        #region properties

        private static TagManager _sInstance;
        private static readonly object SInstanceLocker = new object();

        #endregion

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static TagManager Instance
        {
            get
            {
                lock (SInstanceLocker)
                {
                    return _sInstance ?? (_sInstance = new TagManager());
                }
            }
        }

        #region public functions

        /// <summary>
        /// Gets the tags by ebook.
        /// </summary>
        /// <param name="idBook">The id of the book.</param>
        /// <param name="conn">The connection to the database.</param>
        /// <returns>The list of tags for the book.</returns>
        public List<Tag> GetTagsByEbook(Int64 idBook, SQLiteConnection conn = null)
        {
            List<Tag> tags;

            if (conn != null)
            {
                // Treatment
                tags = GetTagsByEbookTreatment(idBook, conn);
            }
            else
            {
                using (conn = new SQLiteConnection(Connection.CatalogConnection))
                {
                    conn.Open();

                    // Treatment
                    tags = GetTagsByEbookTreatment(idBook, conn);
                }
            }

            return tags;
        }

        #endregion

        #region private functions

        /// <summary>
        /// Gets the tags by ebook (Main treatment).
        /// </summary>
        /// <param name="idBook">The id of the book.</param>
        /// <param name="conn">The connection to the database (opened).</param>
        /// <returns>The list of tags for the book.</returns>
        private static List<Tag> GetTagsByEbookTreatment(Int64 idBook, SQLiteConnection conn)
        {
            var list = new List<Tag>();

            var query = "SELECT t.id, t.name FROM books_tags_link btl INNER JOIN tags t ON btl.tag = t.id WHERE btl.book=" + idBook;
            var cmd = new SQLiteCommand(query, conn);

            // Construction of the files
            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                // New tag
                var tag = new Tag {Id = reader.GetInt64(0), Name = reader.GetString(1)};
                list.Add(tag);
            }

            // Clear the memory
            reader.Dispose();
            cmd.Dispose();

            return list;
        }

        #endregion

        
    }
}
